package com.jianguozh.difs.framework.security.handler;

import cn.hutool.json.JSONUtil;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.common.constant.ApiErrorCode;
import com.jianguozh.difs.framework.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/10 9:11
 */
@Component
public class UnauthorizedHandler implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        ServletUtils.renderString(httpServletResponse, JSONUtil.toJsonStr(R.failed(ApiErrorCode.UNAUTHORIZED)));
    }

}
